package com.z.redis.command.impl.string;

import com.z.redis.RedisCore;
import com.z.redis.command.CommandType;
import com.z.redis.command.WriteCommand;
import com.z.redis.datatype.BytesWrapper;
import com.z.redis.command.Command;
import com.z.redis.datatype.RedisString;
import com.z.redis.resp.BulkString;
import com.z.redis.resp.Resp;
import com.z.redis.resp.SimpleString;
import io.netty.channel.ChannelHandlerContext;

/**
 * SETEX key seconds value
 * 设置键值对 同时指定过期时间
 */
public class SetEx implements WriteCommand {
    private BytesWrapper key;
    private BytesWrapper value;
    private int seconds;

    @Override
    public CommandType type(){
        return CommandType.setex;
    }

    @Override
    public void setContent(Resp[] array){
        key = ((BulkString) array[1]).getContent();
        seconds = Integer.parseInt(((BulkString) array[2]).getContent().toUTF8String());
        value = ((BulkString) array[3]).getContent();
    }

    @Override
    public void handle(ChannelHandlerContext ctx, RedisCore redisCore){
        RedisString redisString = new RedisString(value);
        redisString.setTimeout(System.currentTimeMillis() + (seconds * 1000L)); // 计算过期时间戳
        redisCore.put(key,redisString);
        ctx.writeAndFlush(SimpleString.OK);
    }

    @Override
    public void handle(RedisCore redisCore){
        RedisString redisString = new RedisString(value);
        redisString.setTimeout(System.currentTimeMillis() + (seconds * 1000L)); // 计算过期时间戳
        redisCore.put(key,redisString);
    }
}
